package org.infodavid.common.model;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.infodavid.common.IBuilder;
import org.infodavid.common.ejb.TemplateVersionBean;

/**
 * The Class TemplateTest.
 */
public class TemplateVersionTest extends AbstractBeanTest<ITemplateVersion> {

	/** The Template test. */
	private final TemplateTest templateTest = new TemplateTest(this);

	/** The category test. */
	private final TemplateCategoryTest categoryTest = new TemplateCategoryTest(this);

	/**
	 * Instantiates a new Template version test.
	 */
	public TemplateVersionTest() {
		super();
	}

	/**
	 * Instantiates a new Template version test.
	 * @param mainTest the main test
	 */
	public TemplateVersionTest(final AbstractPersistenceTest mainTest) {
		super(mainTest);
	}

	/**
	 * Populate.
	 * @param count the count
	 * @return the collection< test data>
	 * @throws Exception the exception
	 */
	@Override
	protected List<ITemplateVersion> doCreate(final int count) throws Exception {
		final IBuilder<ITemplateVersion> builder =
		    ModelFactory.getInstance().getBuilder(ITemplateVersion.class);
		final List<ITemplateVersion> items = new ArrayList<ITemplateVersion>(count);
		final List<ITemplate> templates = templateTest.populate(count);
		final ITemplateCategory category = categoryTest.populate(1).get(0);
		final IBuilder<IImageData> imgBuilder = ModelFactory.getInstance().getBuilder(IImageData.class);
		final byte[] bytes = new byte[1024];
		IImageData imageData;
		ITemplateVersion item;
		long key;

		for (int i = 0; i < count; i++) {
			item = builder.create();
			key = System.nanoTime();

			item.setTemplate(templates.get(i));
			item.setArchived(false);
			item.setName("item-" + key);
			item.setCategory(category);
			item.setComment("comment-" + key);
			item.setData(item.getComment().getBytes());
			item.setEncoding("UTF-8");
			item.setLanguage(Locale.getAvailableLocales()[RAND.nextInt(Locale.getAvailableLocales().length)]);
			item.setRevision(i + 1);

			if (!items.isEmpty()) {
				RAND.nextBytes(bytes);

				imageData = imgBuilder.create();

				imageData.setValue(bytes);
				imageData.setType(IImageData.EImageType.values()[RAND.nextInt(IImageData.EImageType
				    .values().length)]);
				item.getImages().put(item.getName(), imageData);
			}

			item.setUser(item.getTemplate().getOwnerDetails().getUser());

			items.add(item);
		}

		return items;
	}

	/**
	 * See super class or interface. (non-Javadoc)
	 * @see org.infodavid.common.model.AbstractBeanTest#getEntityClass()
	 */
	@Override
	public Class<TemplateVersionBean> getEntityClass() {
		return TemplateVersionBean.class;
	}

	/**
	 * See super class or interface. (non-Javadoc)
	 * @see org.infodavid.common.model.AbstractBeanTest#getEntityName()
	 */
	@Override
	public String getEntityName() {
		return ITemplateVersion.class.getSimpleName();
	}
}
